<?php

/**
 * 二维码管理
 *
 * @author Administrator
 */

namespace Operation\Model;

use Think\ITime;
use Think\IFilter;
use Think\IReq;
use Think\IFile;
use Think\JSON;
use Org\Net\myCode;

class Code {

    /**
     * @brief 返回检索条件相关信息
     * @param int $search 条件数组
     * @return array 查询条件（$join,$where）数据组
     */
    public static function getSearchCondition($search, $seller_id = '') {
        $join = array('left join sm_goods as go on c.good_id = go.id');
        $where = array();
        if($seller_id){
            $where[] = "go.seller_id = " . $seller_id;
        }

        //条件筛选处理
        if (isset($search['name']) && isset($search['keywords'])) {
            $name = IFilter::act($search['name'], 'string');
            $keywords = IFilter::act($search['keywords'], 'string');
            if ($keywords) {
                $where[] = $name . " like '%" . $keywords . "%'";
            }
        }

        if (isset($search['status']) && $search['status'] !== '') {
            $status = IFilter::act($search['status'], 'int');
            $where[] = "c.status = " . $status;
        }
        
        if (isset($search['is_del']) && $search['is_del'] !== '') {
            $is_del = IFilter::act($search['is_del'], 'int');
            $where[] = "c.is_del = " . $is_del;
        } else {
            $where[] = "c.is_del != 1";
        }

        if (isset($search['create_time']) && !empty($search['create_time'])) {
            $create_time = explode(",", $search['create_time']);
            // 验证日期
            $is_check_0 = ITime::checkDateTime($create_time[0]);
            $is_check_1 = false;
            if (isset($create_time[1])) {
                $is_check_1 = ITime::checkDateTime($create_time[1]);
            }
            if ($is_check_0 && $is_check_1) {
                // 是否相等
                if ($create_time[0] == $create_time[1]) {
                    $where[] = "c.addtime between '" . ITime::getTime($create_time[0] .' 00:00:00') . "' and '" . ITime::getTime($create_time[0] . '23:59:59') . "'";
                } else {
                    $difference = ITime::getDiffSec($create_time[0] . ' 00:00:00', $create_time[1] . ' 00:00:00');
                    if (0 < $difference) {
                        $where[] = "c.addtime between '" . ITime::getTime($create_time[1] .' 00:00:00') . "' and '" . ITime::getTime($create_time[0] . '23:59:59') . "'";
                    } else {
                        $where[] = "c.addtime between '" . ITime::getTime($create_time[0] .' 00:00:00') . "' and '" . ITime::getTime($create_time[1] . '23:59:59') . "'";
                    }
                }
            } elseif ($is_check_0) {
                $where[] = "c.addtime between '" . ITime::getTime($create_time[0] .' 00:00:00') . "' and '" . ITime::getTime($create_time[0] . '23:59:59') . "'";
            }
        }
        
        $results = array(join("  ", $join), join(" and ", $where));
        unset($join, $where);
        return $results;
    }
    
    /*
     * 生成二维码
     */
    public static function createCode($data) {
        $num = IFilter::act(IReq::get('num'), 'int');

        $good_id = IFilter::act(IReq::get('good_id'), 'int');
        $good = M('goods')->find($good_id);
        //规格
        if ($data['spec_array']) {
            $spec_array = array();
            foreach ($data['spec_array'] as $value) {
                $spec_array[] = JSON::decode($value);
            }
            $spec = JSON::encode($spec_array);
            $spec_data = array(
                'good_id' => $good_id,
                'spec' => $spec,
                'num' => $num,
                'time' => ITime::getDateTime()
            );
            $spec_id = M('code_spec')->add($spec_data);
        }else{
            $spec_id = '';
        }
        
        //二维码保存路径
        $path = "./Public/code/" . $good['seller_id'] . '/' . date('Y/m/d');
        if(!is_dir($path))
    	{
    		IFile::mkdir($path);
    	}
        $url = "http://" . $_SERVER['SERVER_NAME'] . __ROOT__ . "/index.php/Home/Index/index/code/";
        
        //发货地
        $arr = '';
        if (trim(IReq::get('province'))) {
            $arr = trim(IReq::get('province'));
        }
        if (trim(IReq::get('city'))) {
            $arr .= ',' . trim(IReq::get('city'));
        }
        if (trim(IReq::get('area'))) {
            $arr .= ',' . trim(IReq::get('area'));
        }
        if ($arr) {
            $areas = M('areas')->where("area_id in (" . $arr . ")")->select();
            $area = '';
            foreach ($areas as $val) {
                $area .= $val['area_name'];
            }
        }
        
        $max_code = M('code')->field('max(id) as max')->find();
        
        //code 前加省代码
        $seller_Obj = M('seller');
        $seller = $seller_Obj->where(array('id' => $good['seller_id']))->find();
        if($seller['code_pre']){
            $code_pre = substr($data['province'], 0, 2) . '-';
            //镒安消防新疆地区
            //$code_pre = '01301-';
        }  else {
            $code_pre = '';
        }
        //dump($code_pre);die;
        set_time_limit(0);
        for ($i = 0; $i < $num; $i++) {
            $time = time();
            $code = $code_pre . self::makeCode($good, $time, $spec_id, $max_code['max'] + 1, $i, $code_pre);
            $code_data[$i] = array(
                'id' => $max_code['max'] + 1,
                'good_id' => $good_id,
                'goods_no' => IFilter::act(IReq::get('goods_no')),
                'spec' => $spec_id,
                'code' => $code,
                'addtime' => $time,
                'img' => $path . '/' . md5($code) . ".png",
                'area' => $area ? $area : '',
                'status' => 1,
                'isok' => 1,
                'isdown' => 1,
                'isout' => 0
            );
            $dataCode = $url . $code;
            myCode::getInstance()->getCode()->png($dataCode, $path . '/' . md5($code) . ".png");
            $max_code['max'] = $max_code['max'] + 1;
        }
        $codeDB = M('code');
        $res = $codeDB->addAll($code_data);
        //dump($res);die;
        if($res){
            return $num;
        }  else {
            return FALSE;
        }
    }
    
    /*
     * 生成防伪码
     */
    private static function makeCode($good, $time, $spec_id, $code_id, $i, $code_pre){
        $cat_code = $good['fourth'] ? $good['fourth'] : ($good['third'] ? $good['third'] : ($good['second'] ? $good['second'] : ($good['first'] ? $good['first'] : $good['cat'])));
        $spec_code = $code_id . $spec_id;
        $time = $time . sprintf("%05d", $i);

        $code = $cat_code . $spec_code . $good['barcode'] . $time;
        
        $srt_array = myCode::shorturl($code);
        $codeDB = M('code');
        foreach ($srt_array as $value) {
            if(!$codeDB->where(array('code' => $code_pre . $value))->find()){
                return $value;
            }  else {
                self::makeCode($good, $time, $spec_id, $code_id, $i, $code_pre);
            }
        }
    }
    
    

}
